<template>
  <div class="ai-chat-container">
    <!-- 主聊天区域 -->
    <div class="chat-main">
      <!-- 消息列表 -->
      <div class="messages-container">
        <div v-for="(message, index) in messages" :key="index" :class="['message', message.role]">
          <div class="avatar">
            <el-icon v-if="message.role === 'user'"><User /></el-icon>
            <el-icon v-else style="color: #10a37f;"><Robot /></el-icon>
          </div>
          <div class="message-content">
            <div class="message-bubble">
              {{ message.content }}
            </div>
            <div class="message-time">
              {{ formatTime(message.timestamp) }}
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <el-input
          v-model="inputMessage"
          placeholder="输入您的问题..."
          @keyup.enter="sendMessage"
          class="message-input"
          :disabled="isLoading"
        >
          <template #append>
            <el-button 
              :loading="isLoading" 
              @click="sendMessage"
              type="primary"
              :disabled="!inputMessage.trim()"
            >
              <el-icon v-if="!isLoading"><Send /></el-icon>
              发送
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h3>聊天记录</h3>
        <el-button type="text" @click="clearChat" size="small">
          清空
        </el-button>
      </div>
      <div class="chat-history">
        <div 
          v-for="(chat, index) in chatHistory" 
          :key="index"
          class="history-item"
          @click="loadChat(chat)"
        >
          <el-icon><ChatLineRound /></el-icon>
          <span>对话 {{ index + 1 }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { User, Robot, Send, ChatLineRound } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const messages = ref([])
const inputMessage = ref('')
const isLoading = ref(false)
const chatHistory = ref([])

// 模拟AI回复
const simulateAIResponse = async (userMessage) => {
  isLoading.value = true
  await new Promise(resolve => setTimeout(resolve, 1000 + Math.random() * 2000))
  
  const responses = [
    "您好！我是AI助手，很高兴为您服务。请问有什么可以帮助您的吗？",
    "我理解您的问题了。让我为您提供一些相关信息...",
    "根据您的描述，我建议您可以考虑以下几个方面：",
    "这是一个很好的问题！让我为您详细解释一下：",
    "感谢您的提问。关于这个问题，我的看法是：",
    "我注意到您对这方面很感兴趣。让我为您提供更深入的分析："
  ]
  
  return responses[Math.floor(Math.random() * responses.length)]
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  const userMessage = {
    role: 'user',
    
    content: inputMessage.value.trim(),
    timestamp: new Date()
  }
  
  messages.value.push(userMessage)
  const currentInput = inputMessage.value
  inputMessage.value = ''
  
  try {
    const aiResponse = await simulateAIResponse(currentInput)
    const aiMessage = {
      role: 'assistant',
      content: aiResponse,
      timestamp: new Date()
    }
    messages.value.push(aiMessage)
    
    // 保存到聊天历史
    saveChatHistory()
  } catch (error) {
    ElMessage.error('发送消息失败')
  } finally {
    isLoading.value = false
  }
  
  // 滚动到底部
  nextTick(() => {
    const container = document.querySelector('.messages-container')
    if (container) {
      container.scrollTop = container.scrollHeight
    }
  })
}

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

const clearChat = () => {
  messages.value = []
  ElMessage.success('聊天已清空')
}

const saveChatHistory = () => {
  if (messages.value.length > 0) {
    localStorage.setItem('aiChatHistory', JSON.stringify(messages.value))
  }
}

const loadChatHistory = () => {
  const saved = localStorage.getItem('aiChatHistory')
  if (saved) {
    messages.value = JSON.parse(saved)
  }
}

const loadChat = (chat) => {
  messages.value = chat
}

onMounted(() => {
  loadChatHistory()
})
</script>

<style scoped>
.ai-chat-container {
  display: flex;
  height: calc(100vh - 140px);
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.messages-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #f7f7f8;
}

.message {
  display: flex;
  margin-bottom: 20px;
  gap: 12px;
}

.message.user {
  flex-direction: row-reverse;
}

.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.message.user .avatar {
  background: #10a37f;
  color: white;
}

.message-content {
  max-width: 70%;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 18px;
  line-height: 1.4;
  word-wrap: break-word;
}

.message.assistant .message-bubble {
  background: white;
  border: 1px solid #e5e5e5;
  border-bottom-left-radius: 4px;
}

.message.user .message-bubble {
  background: #10a37f;
  color: white;
  border-bottom-right-radius: 4px;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.message.user .message-time {
  text-align: left;
}

.input-area {
  padding: 20px;
  border-top: 1px solid #e5e5e5;
  background: white;
}

.message-input {
  border-radius: 20px;
}

.sidebar {
  width: 280px;
  border-left: 1px solid #e5e5e5;
  background: #fafafa;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #e5e5e5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.chat-history {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
  gap: 8px;
}

.history-item:hover {
  background: #e8e8e8;
}

.history-item .el-icon {
  color: #666;
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar,
.chat-history::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track,
.chat-history::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.messages-container::-webkit-scrollbar-thumb,
.chat-history::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover,
.chat-history::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    display: none;
  }
  
  .message-content {
    max-width: 85%;
  }
}
